//
//  SJLocationManager.m
//  ProjectForBD
//
//  Created by Jaesun on 17/5/23.
//  Copyright © 2017年 B.D. All rights reserved.
//

#import "SJLocationManager.h"

@interface SJLocationManager ()

@property (nonatomic, strong) CLLocation *location;

@property (nonatomic, assign) NSDate *lastLocationTime;

@end

@implementation SJLocationManager
static SJLocationManager *manager = nil;


+ (instancetype)shareManager {
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[SJLocationManager alloc] init];
    });
    return manager;
}

/**
 *  反地理编码：经纬度坐标—>地名
 */
- (void)reverseGeocodeWithCLLocation:(CLLocation *)location Complete:(SJLocationReverseGeocodeBlock) locationReverseGeocodeBlock  {
    
    // CLLocation *locationNow = [[CLLocation alloc] initWithLatitude: [latitude floatValue] longitude:[longitude floatValue]];
    
    CLGeocoder *gecoder = [[CLGeocoder alloc] init];
    self.locationReverseGeocodeBlock = locationReverseGeocodeBlock;
    //2.反地理编码
    [gecoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error) {
        if (error||placemarks.count == 0) { //编码失败
            if (self.locationReverseGeocodeBlock) {
                self.locationReverseGeocodeBlock(NO,nil);
            }
        }
        else {
            // 显示最前面的地标信息
            CLPlacemark *firstPlacemark = [placemarks firstObject];
            if (self.locationReverseGeocodeBlock) {
                self.locationReverseGeocodeBlock(YES,firstPlacemark);
            }
        }
    }];
}

- (void)updateLoactionWithComplete:(SJLocationCompleteBlock)locationCompleteBlock {
    
    self.location = nil;
    [self.locationManager requestWhenInUseAuthorization];
    self.locationManager = [[CLLocationManager alloc] init];
    self.locationManager.delegate = self;
    self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    self.locationManager.distanceFilter = 10.0f;
    self.locationManager.distanceFilter = kCLDistanceFilterNone;
    [self.locationManager requestWhenInUseAuthorization];//（当用户使用时）
    self.locationCompleteBlock = locationCompleteBlock;
    
    // 判断是否可以定位 并且 打开了定位服务
    NSLog(@"定位状态码: %d",[CLLocationManager authorizationStatus]);
    
    if ([CLLocationManager locationServicesEnabled] &&
        [CLLocationManager authorizationStatus] != kCLAuthorizationStatusDenied) {
            //定位功能可用，开始定位
            [self.locationManager startUpdatingLocation];
        }
    else {
        
        NSLog(@"Not support location severs");
        if (self.locationCompleteBlock) {
            self.locationCompleteBlock(NO,nil);
        }
    }
}

- (void)updateLoactionPlaceMarkWithComplete:(SJLocationPlacemarkBlock)locationPlacemarkBlock {
    
    self.location = nil;
    [self.locationManager requestWhenInUseAuthorization];
    self.locationManager = [[CLLocationManager alloc] init];
    self.locationManager.delegate = self;
    self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    self.locationManager.distanceFilter = 10.0f;
    self.locationManager.distanceFilter = kCLDistanceFilterNone;
    self.locationPlacemarkBlock = locationPlacemarkBlock;
    
    // 判断是否可以定位 并且 打开了定位服务
    NSLog(@"定位状态码: %d",[CLLocationManager authorizationStatus]);
    
    if ([CLLocationManager locationServicesEnabled] &&
        [CLLocationManager authorizationStatus] != kCLAuthorizationStatusDenied) {
        //定位功能可用，开始定位
        [self.locationManager startUpdatingLocation];
    }
    else {
        NSLog(@"Not support location severs");
        if (self.locationCompleteBlock) {
            self.locationCompleteBlock(NO,nil);
        }
    }
}

// 位置更新代理方法
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations {
    
    CLLocation *newLocation = locations.lastObject;    
    if (newLocation.horizontalAccuracy < 0) {
        NSLog(@"Not support location severs");
        if (self.locationCompleteBlock) {
            self.locationCompleteBlock(NO,nil);
        }
        return; // 经纬度无效
    }
    if (self.location) return; // 已经定位成功
    
    self.location = newLocation;
    [self.locationManager stopUpdatingLocation];
    
    CLLocationCoordinate2D curLocation = newLocation.coordinate;
    NSLog(@"当前的经纬度是%f %f",curLocation.latitude,curLocation.longitude);
    
    if (self.locationCompleteBlock) {
        self.locationCompleteBlock(YES,newLocation);
    }
}

@end
